package com.shuyuntu.proposal.dao.hib;

import com.shuyuntu.proposal.dao.IArticleDao;
import com.shuyuntu.proposal.dao.base.BaseDaoHib;
import com.shuyuntu.proposal.entity.Article;
import com.shuyuntu.proposal.entity.Proposal;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by limeng on 16/8/22.
 */
@Repository("articleDao")
public class ArticleDaoHib extends BaseDaoHib<Article, Integer> implements IArticleDao {
    @Override
    public List<Article> querySearchPageList(Integer pageNo, Integer pageSize,
                                             StringBuffer rowCount, Order order, Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);

        criteria.setProjection(Projections.projectionList()
                .add(Projections.property("id"), "id")
                .add(Projections.property("title"), "title")
                .add(Projections.property("author"), "author")
                .add(Projections.property("createTime"), "createTime")
                .add(Projections.property("updateTime"), "updateTime")
                .add(Projections.property("type"), "type")
                .add(Projections.property("clickCount"), "clickCount")
        ).setResultTransformer(Transformers.aliasToBean(Article.class));

        for (Criterion criterion : criterions) {
            if (criterion != null) {
                criteria.add(criterion);
            }
        }
        if (rowCount != null) {
            rowCount.append(queryCount(criterions));
        }
        if (order != null) {
            criteria.addOrder(order);
        }

        List<Article> list = criteria.setFirstResult((pageSize * (pageNo - 1))).setMaxResults(pageSize).list();
        return list;
    }
}
